package com.example.project22_editingmediaplayer.service;

import java.util.ArrayList;

import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.os.Parcelable;
import android.util.Log;

import com.example.project22_editingmediaplayer.MainActivity;
import com.example.project22_editingmediaplayer.action.AudioUltility;
import com.example.project22_editingmediaplayer.objects.SongObject;
import com.example.provider.SamsungProvider;
import com.example.provider.TblInfoSong;
import com.example.provider.TblSong;

public class DatabaseService extends Service {
	Context myContext;
	public ArrayList<SongObject> arraySong;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		myContext = this;
		super.onCreate();

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		if (intent.getAction().equals(MainActivity.INSERT_SONG)) {
			int idd = intent.getExtras().getInt("id", -1);
			Log.d("idid", String.valueOf(idd));
			int flag = intent.getExtras().getInt("flag", 0);
			Log.d("flag", String.valueOf(flag));
			addSong(idd, flag);
		}
		if (intent.getAction().equals(MainActivity.DELETE_SONG)) {
			int id = intent.getExtras().getInt("idDelete");
			deleteSong(id);
		}
		if (intent.getAction().equals(MainActivity.UPDATE_SONG)) {
			SongObject so = intent.getParcelableExtra("songUpdate");
			updateSong(so);
		}
		if(intent.getAction().equals(MainActivity.GET_SONG_BY_RATING)){
			ArrayList<SongObject> listsongRating =getSongByRating();
			Log.e("ratin",String.valueOf(listsongRating.size()));
			Intent i = new Intent();
			i.setAction(MainActivity.GET_SONG_BY_RATING);
			i.putExtra("value", (ArrayList<? extends Parcelable>) listsongRating); 
			sendBroadcast(i);
		}
		return super.onStartCommand(intent, flags, startId);
	}
	
	
	public ArrayList<SongObject> getSongByRating() {
		ArrayList<SongObject> arrsongByRating = new ArrayList<SongObject>();
		AudioUltility audioUltility = new AudioUltility(myContext);
		String sortBy=TblInfoSong.SONG_RATING + " DESC";
		Log.e("sortby",sortBy);
		
		Cursor c = myContext.getContentResolver().query(
				SamsungProvider.URI_INFO, null,null,null, sortBy);
		if (c != null) {
			while (c.moveToNext()&&c.getPosition()<10) {
				
				arrsongByRating
						.add(new SongObject(
								c.getInt(c
										.getColumnIndexOrThrow(TblInfoSong.SONG_ID)),
								audioUltility
										.getOneSongById(
												c.getInt(c
														.getColumnIndexOrThrow(TblInfoSong.SONG_ID)))
										.get_path(),
								audioUltility
										.getOneSongById(
												c.getInt(c
														.getColumnIndexOrThrow(TblInfoSong.SONG_ID)))
										.get_name(),
								audioUltility
										.getOneSongById(
												c.getInt(c
														.getColumnIndexOrThrow(TblInfoSong.SONG_ID)))
										.get_artist(),
								c.getInt(c
										.getColumnIndexOrThrow(TblInfoSong.SONG_RATING))));
			}
			c.close();
			return arrsongByRating;
		} else {
			c.close();
			return null;
		}
	}

	public void updateSong(SongObject so) {
		int id = so.get_id();
		boolean check=true;
		ContentValues values = new ContentValues();
		values.put(TblInfoSong.SONG_ID, so.get_id());
		values.put(TblInfoSong.SONG_RATING, so.get_rating());
		ArrayList<SongObject> ab=getSongByRating();
		try {
			for(int i=0;i<ab.size();i++){
				check=check&&(ab.get(i).get_id()!=id);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		if(check){
			Log.e("insert", "true");
			myContext.getContentResolver().insert(SamsungProvider.URI_INFO,
					values);
		}
		else{
			// TODO: handle exception
			Log.e("update", "true");
			myContext.getContentResolver().update(SamsungProvider.URI_INFO,
					values, TblInfoSong.SONG_ID + "=" + id, null);
		}
	}

	public void deleteSong(int id) {
		myContext.getContentResolver().delete(SamsungProvider.URI_SONG,
				TblSong.SONG_ID + "=" + id, null);
		myContext.getContentResolver().delete(SamsungProvider.URI_INFO,
				TblInfoSong.SONG_ID + "=" + id, null);
	}

	// add a song into sad album of database
	public void addSong(int idd, int flg) {
		boolean check = true;
		ArrayList<SongObject> a = new ArrayList<SongObject>();
		a = getIdToCheck(flg);
		if (a != null) {
			Log.e("so phan tu trong database", String.valueOf(a.size()));
			for (int i = 0; i < a.size(); i++) {
				Log.e("id song la bao nhie", String.valueOf(a.get(i)));
				check = check && (idd != a.get(i).get_id());
			}
		} else {
		}
		if (check) {
			switch (flg) {
			case 3:
				ContentValues contentValues3 = new ContentValues();
				contentValues3.put(TblSong.SONG_ID, idd);
				contentValues3.put(TblSong.SONG_GENRE, "sad");
				getContentResolver().insert(SamsungProvider.URI_SONG,
						contentValues3);
				break;
			case 1:
				ContentValues contentValues1 = new ContentValues();
				contentValues1.put(TblSong.SONG_ID, idd);
				contentValues1.put(TblSong.SONG_GENRE, "happy");
				getContentResolver().insert(SamsungProvider.URI_SONG,
						contentValues1);
				break;
			case 0:
				ContentValues contentValues0 = new ContentValues();
				contentValues0.put(TblSong.SONG_ID, idd);
				contentValues0.put(TblSong.SONG_ISFAVORITE, "yes");
				getContentResolver().insert(SamsungProvider.URI_SONG,
						contentValues0);
				break;
			case 2:
				ContentValues contentValues2 = new ContentValues();
				contentValues2.put(TblSong.SONG_ID, idd);
				contentValues2.put(TblSong.SONG_GENRE, "funny");
				getContentResolver().insert(SamsungProvider.URI_SONG,
						contentValues2);
				break;
			}

		} else {
			// do nothing
		}

	}

	public ArrayList<SongObject> getIdToCheck(int flag) {
		ArrayList<SongObject> arrayList = new ArrayList<SongObject>();
		AudioUltility audioUltility = new AudioUltility(myContext);
		Cursor c = null;
		switch (flag) {
		case 0:
			c = myContext.getContentResolver().query(SamsungProvider.URI_SONG,
					null, TblSong.SONG_ISFAVORITE + " =?",
					new String[] { "yes" }, null);
			break;
		case 1:
			c = myContext.getContentResolver().query(SamsungProvider.URI_SONG,
					null, TblSong.SONG_GENRE + " =?", new String[] { "happy" },
					null);
			break;
		case 2:
			c = myContext.getContentResolver().query(SamsungProvider.URI_SONG,
					null, TblSong.SONG_GENRE + " =?", new String[] { "funny" },
					null);
			break;
		case 3:
			c = myContext.getContentResolver().query(SamsungProvider.URI_SONG,
					null, TblSong.SONG_GENRE + " =?", new String[] { "sad" },
					null);
			break;
		}
		if (c != null) {
			while (c.moveToNext()) {
				arrayList
						.add(new SongObject(
								c.getInt(c
										.getColumnIndexOrThrow(TblSong.SONG_ID)),
								audioUltility
										.getOneSongById(
												c.getInt(c
														.getColumnIndexOrThrow(TblSong.SONG_ID)))
										.get_path(),
								audioUltility
										.getOneSongById(
												c.getInt(c
														.getColumnIndexOrThrow(TblSong.SONG_ID)))
										.get_name(),
								audioUltility
										.getOneSongById(
												c.getInt(c
														.getColumnIndexOrThrow(TblSong.SONG_ID)))
										.get_artist(),
								c.getString(c
										.getColumnIndexOrThrow(TblSong.SONG_GENRE)),
								c.getString(c
										.getColumnIndexOrThrow(TblSong.SONG_ISFAVORITE))));

			}
			c.close();
			return arrayList;
		} else {
			c.close();
			return null;
		}

	}

}
